package com.antgroup.seckill.business.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author wangxy
 * @date 2024/7/27 14:41
 */
public class CookieUtil {

    // 设置 Cookie
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    // 获取 Cookie
    public static Optional<Cookie> getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            return Arrays.stream(cookies)
                    .filter(cookie -> name.equals(cookie.getName()))
                    .findFirst();
        }
        return Optional.empty();
    }

    // 删除 Cookie
    public static void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    // 获取 Cookie 的值
    public static String getCookieValue(HttpServletRequest request, String name) {
        return getCookie(request, name).map(Cookie::getValue).orElse(null);
    }

    // 判断 Cookie 是否存在
    public static boolean isCookieExists(HttpServletRequest request, String name) {
        return getCookie(request, name).isPresent();
    }
}
